        mapboxgl.accessToken = 'pk.eyJ1IjoicmtscmFxbmp3ZiIsImEiOiJjbTJvcGZyeXgwaXM5MnFweXcyaGgwcHczIn0.rSNdUCodQHP3167T5lRtSA';  // 替换为你自己的 Mapbox 访问令牌
        const map = new mapboxgl.Map({
            container: 'map',
            style: 'mapbox://styles/rklraqnjwf/cm8ubjmpd00z101sr2absblcf/draft',
            
            center: [102.1870, 38.5161], // starting position [lng, lat]
            zoom: 10, // starting zoom
        });

        let donutChartMarkers = [];  // 存储地图上每个饼状图的标记
        let activePopup = null; // 用来存储当前显示的popup
        let isIncomeData = false;  // 用来切换显示的状态，默认是显示贫困原因
        d3.selectAll(".legend1")
        .style("opacity", 1);
        d3.selectAll(".legend2")
        .style("opacity", 0);
        
        // 读取 GeoJSON 文件
fetch('./data/村级人口及收入分布统计.geojson')
.then(response => response.json())
.then(data => {
    processVillageData(data.features);
})
.catch(error => console.error('Error loading GeoJSON:', error));
      console.log(d3.selectAll(".donut-chart"))  
        function processVillageData(villageData) {
            villageData.forEach(feature => {
                const longitude = feature.geometry.coordinates[0];
                const latitude = feature.geometry.coordinates[1];
                const properties = feature.properties;

                const population = properties.人口总数;
                
                const villageName = properties.村;
                const income=properties['工资性收入']+properties['公益性岗位收入']+ properties['其他工资性收入']+ properties['财产性收入(合计)']+
                properties['转移性收入']+ properties['生产经营性收入(合计)'];
                
                const povertyCauses = [
                    properties["因丧"], properties["因婚"], properties["因学"], properties["因残"], properties["因灾"],
                    properties["因病"], properties["缺劳力"], properties["缺土地"], properties["缺技术"], properties["缺水"],
                    properties["缺资金"], properties["自身发展动力不足"], properties["其他"]
                ];
        
                const incomeTypes = [
                    properties["工资性收入"], properties["公益性岗位收入"], properties["其他工资性收入"],
                    properties["财产性收入(合计)"], properties["转移性收入"], properties["生产经营性收入(合计)"]
                ];
                if(isIncomeData){
                    createDonutChart(longitude, latitude, income, villageName, incomeTypes);
                }else{
                createDonutChart(longitude, latitude, population, villageName, povertyCauses);}
                
               
            });
            
        }

        function createDonutChart(longitude, latitude, population, villageName, povertyCauses) {
            const chartElement = document.createElement('div');
            chartElement.className = 'donut-chart';
            chartElement.style.zIndex = '1000';
            
           

            
            const minRadius = 25;
            const maxRadius = 100;
            
            let chartRadius = Math.max(minRadius, Math.min(maxRadius, population / 10));
            if(isIncomeData){
                chartRadius = Math.max(minRadius, Math.min(maxRadius, population / 6000));
            }
            let arcData = povertyCauses.map(function(cause) {
                return { value: cause * 100 };
            });

            const width = 100;
            const height = 100;

            const svg = d3.select(chartElement).append('svg')
                .attr('width', width)
                .attr('height', height)
                
                .append('g')
                .attr('transform', `translate(${width/2}, ${height / 2})`);

            const angleSlice = Math.PI * 2 / povertyCauses.length;
            const pie = d3.pie().value(function(d) { return d.value; });
            const arc = d3.arc().innerRadius(0).outerRadius(chartRadius);

            

            const arcs = svg.selectAll('g.arc')
                .data(pie(arcData))
                .enter().append('g')
                .attr('class', 'arc');

            arcs.append('path')
                .attr('d', arc)
                .attr('fill', function(d, i) {
                    const colors = ['#FF9999', '#66B3FF', '#99FF99', '#FFCC99', '#FF9966', '#66FF66', '#FF66CC', '#FF6699', '#CC99FF', '#CCCCFF', '#99CCFF', '#FFCCFF', '#E0E0E0'];
                    return colors[i];
                });

           

            
            const mapMarker = new mapboxgl.Marker(chartElement)
                .setLngLat([longitude, latitude])
                .addTo(map);

            donutChartMarkers.push({ longitude, latitude, chartElement, mapMarker, villageName, population });
            
            // 添加鼠标悬浮事件
            chartElement.addEventListener('mouseenter', function() {
                
                if (activePopup) {
                    activePopup.remove();
                }

               if(!isIncomeData){ // 创建新的弹出框
                activePopup = new mapboxgl.Popup({ offset: [30, 0], closeButton: false, className: 'popup' })
                    .setLngLat([longitude, latitude])
                    .setHTML(`<strong>地名: ${villageName}</strong><br><strong>脱贫人口: ${population}</strong>`)
                    .addTo(map);
               }
               if(isIncomeData){
                activePopup = new mapboxgl.Popup({ offset: [20, 0], closeButton: false, className: 'popup' })
                    .setLngLat([longitude, latitude])
                    .setHTML(`<strong>地名: ${villageName}</strong><br><strong>总收入: ${population.toFixed(2)}</strong>`)
                    .addTo(map);
               }
            });

            // 添加鼠标离开事件
            chartElement.addEventListener('mouseleave', function() {
                
                // 移除弹出框
                if (activePopup) {
                    activePopup.remove();
                    activePopup = null;
                }
            });
        }



        // 按钮点击事件切换数据
document.getElementById('toggleDataButton').addEventListener('click', function() {
    isIncomeData = !isIncomeData;
    if(isIncomeData){
        d3.selectAll(".legend1")
        .style("opacity", 0);
        d3.selectAll(".legend2")
        .style("opacity", 1);
        
    }else{
        d3.selectAll(".legend1")
        .style("opacity", 1);
        d3.selectAll(".legend2")
        .style("opacity", 0);
    }

    donutChartMarkers.forEach(function(marker) {
        marker.chartElement.remove();  // 移除现有的饼状图
    });
    donutChartMarkers = [];  // 清空标记数组
    
    // 重新生成图表
    fetch('./data/村级人口及收入分布统计.geojson')
        .then(response => response.json())
        .then(data => processVillageData(data.features))
        .catch(error => console.error('Error reloading GeoJSON:', error));
});








